<?php

namespace tmcore\services\notice\system;

use app\common\enum\MsgEnum;
use app\common\model\notice\UserNoticeLog;
use tmcore\services\notice\BaseNotice;

class SystemSendService extends BaseNotice
{
    /**
     * 发送消息
     * @param $config
     * @param $params ['uid' => '用户id', 'account' => '账号名称', 'expire_time' => '验证码过期时间', 'template' => '系统模板参数']
     * @param bool $is_async
     * @return bool|mixed
     */
    public function send($config, $params, $is_async = false) {

        if(empty($params['template'])) return self::setError('参数校验失败');
        if($config['is_captcha'] && empty($params['template']['code'])) return self::setError('参数校验失败');

        try {
            $notice_log = UserNoticeLog::create([
                'scene'       => $config['scene'],
                'msg_token'   => $config['msg_token'],
                'uid'         => $params['uid']??0,
                'account'     => $params['account']??'',
                'title'       => $config['name'],
                'code'        => $config['is_captcha']?$params['template']['code']:'',
                'content'     => $this->getContent($params['template'], $config['system_template']['content']??''),
                'error'       => '',
                'notice_type' => $config['type'],
                'send_type'   => MsgEnum::SYS_TYPE,
                'status'      => 0,
                'is_read'     => 0,
                'is_captcha'  => $config['is_captcha'],
                'expire_time' => $params['expire_time']??time()+900,
            ]);

            if(!empty($notice_log['id'])) $this->sendSuccess($notice_log['id']);
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }
}